package com.lin.filter;

import com.lin.entity.SecurityUser;
import com.lin.util.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lin
 * @version 1.0
 * @Description
 * @Date 2021/1/21 18:03
 */
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String tokenHeader = request.getHeader(JwtUtil.TOKEN_HEADER);
        if (tokenHeader == null || !tokenHeader.startsWith(JwtUtil.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(this.getAuthentication(tokenHeader));
        super.doFilterInternal(request, response, chain);
    }

    private Authentication getAuthentication(String tokenHeader) {
        String token = tokenHeader.substring(JwtUtil.TOKEN_PREFIX.length());
        SecurityUser securityUser = JwtUtil.getSecurityUserFromToken(token);
        if (securityUser == null) return null;
        return new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());

    }
}
